package thread;

import java.util.function.IntConsumer;

public class leetCode1116 {
    private int n;
    private final Object lock = new Object();
    private int state = 1;

    public leetCode1116(int n) {
        this.n = n;
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        synchronized (lock) {
            for (int i = 1; i <= n; i++) {
                while (state != 1) {
                    lock.wait();
                }
                printNumber.accept(0);
                if (i % 2 == 1) {
                    state = 3;
                } else {
                    state = 2;
                }
                lock.notifyAll();
            }
        }

    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        synchronized (lock){
            for (int i = 2; i <= n; i+=2) {
                while (state != 2){
                    lock.wait();
                }
                printNumber.accept(i);
                state = 1;
                lock.notifyAll();
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        synchronized (lock){
            for (int i = 1; i <= n; i+=2) {
                while (state != 3){
                    lock.wait();
                }
                printNumber.accept(i);
                state = 1;
                lock.notifyAll();
            }
        }
    }
}
